//
//  AppDelegate.m
//  HB
//
//  Created by 孙智慧 on 16/1/4.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import "LeftSortsViewController.h"
#import "AdvertPage.h"
#import "LoginPage.h"
#import "MusicPlayController.h"
#import "PaySuccController.h"

@implementation AppDelegate


+ (AppDelegate *)appDeg
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

- (void)showHomePage:(BOOL)isLogin
{
    if(isLogin)
    {
#pragma 登陆状态显示这个
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
        UITabBarController *mainVC = (UITabBarController *)[storyboard instantiateViewControllerWithIdentifier:@"tabbar"];
        
        //设置bar图
        // 拿到 TabBar 在拿到想应的item
        UITabBar *tabBar = mainVC.tabBar;
        UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
        UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
        UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
        UITabBarItem *item3 = [tabBar.items objectAtIndex:3];
        UITabBarItem *item4 = [tabBar.items objectAtIndex:4];
        
        // 对item设置相应地图片
        UIColor *testColor1= [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
        tabBar.tintColor=testColor1;
        
        item0.selectedImage = [[UIImage imageNamed:@"RecommendSelect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item0.image = [[UIImage imageNamed:@"Recommend"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item0.title=@"推荐";
        
        item1.selectedImage = [[UIImage imageNamed:@"citySelect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item1.image = [[UIImage imageNamed:@"city"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item1.title=@"同城";
        
        item2.selectedImage = [[UIImage imageNamed:@"MusicSelect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item2.image = [[UIImage imageNamed:@"Music"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item2.title=@"曲库";
        
        item3.selectedImage = [[UIImage imageNamed:@"celebritySelect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item3.image = [[UIImage imageNamed:@"celebrity"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item3.title=@"圈子";
        
        item4.selectedImage = [[UIImage imageNamed:@"mineSelect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item4.image = [[UIImage imageNamed:@"mine"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        item4.title=@"我的";
        
        self.window.rootViewController = mainVC;
    }
    else
    {
#pragma 未登陆状态显示这个
        
        LoginPage *loginPage=[[LoginPage alloc] init];
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginPage];
        
        self.window.rootViewController = nav;
        
    }
    [self.window makeKeyAndVisible];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    [AdvertPage showAdvertPage];
    
    //步骤2 设置状态栏的颜色
    application.statusBarStyle = UIStatusBarStyleLightContent;
    
    [[FxGlobal global].push registerPush];
    
    [self updateNotification:application];
    
    //注册微信
    [WXApi registerApp:WXAppID];
    
    return YES;
    //步骤3 在plist里面设置View controller-based status bar appearance 为 NO
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    
}



//响应远程音乐播放控制消息
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
    
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) {
                
            case UIEventSubtypeRemoteControlTogglePlayPause:
                //[[PlayController sharedInstance] pause];
                
                [[MusicPlayController sharedMyClass] playOrPause];
                
                NSLog(@"RemoteControlEvents: pause");
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                //[[PlayController sharedInstance] playModeNext];
                [[MusicPlayController sharedMyClass] nextMusic];
                NSLog(@"RemoteControlEvents: playModeNext");
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                //[[PlayController sharedInstance] playPrev];
                [[MusicPlayController sharedMyClass] preMusic];
                NSLog(@"RemoteControlEvents: playPrev");
                break;
            case UIEventSubtypeRemoteControlPause:
                [[MusicPlayController sharedMyClass] playOrPause];
                NSLog(@"RemoteControlEvents: Pause");
                break;
            case UIEventSubtypeRemoteControlPlay:
                [[MusicPlayController sharedMyClass] playOrPause];
                NSLog(@"RemoteControlEvents: Play");
                break;
            default:
                break;
        }
    }
}



- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
    return  isSuc;
}

-(void) onReq:(BaseReq*)req
{
    if([req isKindOfClass:[GetMessageFromWXReq class]]) {
        BASE_INFO_FUN(@"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信");
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]]) {
        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        WXMediaMessage *msg = temp.message;
        WXAppExtendObject *obj = msg.mediaObject;
        
        //显示微信传过来的内容
        BASE_INFO_FUN(msg.title);
        BASE_INFO_FUN(msg.description);
        BASE_INFO_FUN(obj.extInfo);
    }
    else if([req isKindOfClass:[LaunchFromWXReq class]]) {
        BASE_INFO_FUN(@"从微信启动");
    }
}

-(void) onResp:(BaseResp*)resp
{
    
    if ([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        BASE_INFO_FUN(([NSString stringWithFormat:@"发送媒体消息结果:%@",@(resp.errCode)]));
    }
    else if ([resp isKindOfClass:[SendAuthResp class]])
    {
        
    }
    else if ([resp isKindOfClass:[AddCardToWXCardPackageResp class]])
    {
        
    }
    else if([resp isKindOfClass:[PayResp class]])
    {
        NSString *orderCode=[Common getUserDefaults:@"OrderCode"];
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg;
        
        switch (resp.errCode)
        {
            case WXSuccess:
            {
                PaySuccController *paySucc=[[PaySuccController alloc] init];
                
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:paySucc];
                
                self.window.rootViewController = nav;
                
                strMsg =   @"支付结果：成功！";
                
                NSLog(@"支付成功－PaySuccess,订单号:%@,retcode = %d", orderCode, resp.errCode);
                
                break;
            }
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d,订单号:%@,retstr = %@", resp.errCode,orderCode,resp.errStr);
                break;
                
                
        }
        
        PaySuccController *paySucc=[[PaySuccController alloc] init];
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:paySucc];
        
        self.window.rootViewController = nav;
    }
    
}

#pragma mark - APNS

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [[FxGlobal global].push bindDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    BASE_ERROR_FUN(error);
}


#pragma mark Local And Push Notification

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [self showNotification:userInfo];
    
    [self updateNotification:application];
    
    [[FxGlobal global].push handleNotification:userInfo];
    
}

- (void)showNotification:(NSDictionary*)userInfo
{
    NSString *message = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
    
    BASE_INFO_FUN(message);
}

- (void)updateNotification:(UIApplication *)application
{
    [application cancelAllLocalNotifications];
    
    [application setApplicationIconBadgeNumber:0];
}

@end
